const express = require("express");
const router = express.Router();

// 连接数据库
const db = require("../utils/db");

// jwt 将用户信息加密成token
const jwt = require("jsonwebtoken");
// 密钥
const secretKey = "liuhailang";

// 登录路由
router.post("/api/login", (req, res) => {
  let userObj = req.body;
  console.log(userObj);
  const { username, password } = userObj;
  const tokenStr = jwt.sign(
    // 三个参数 1.加密的数据 2.密钥 3.过期时间
    { username },
    secretKey,
    { expiresIn: "1h" }
  );

  // 获取前端传来的数据，查询数据库是否存在该用户
  db.query(
    "select * from users where username=? and password=?",
    [username, password],
    (err, data) => {
      if (data.length === 0) {
        res.send({ code: 500, msg: "用户名或密码错误" });
      } else {
        const user = data[0]; // 获取查询到的用户信息
        const { id, username } = user;
        // 更新token
        db.query(
          "update users set token=? where username=?",
          [tokenStr, username],
          (err, data) => {
            if (err) {
              console.log(err);
              res.send({ code: 500, msg: "服务器错误" });
            } else {
              res.send({
                code: 200,
                msg: "欢迎登录",
                username,
                id,
                token: tokenStr, //发送token给用户
              });
            }
          }
        );
      }
    }
  );
});

module.exports = router;
